package com.njcb.ams.support.validation.constraints;

/**
 * @author liuyanlong
 */

import com.njcb.ams.support.codevalue.EnumCode;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
        validatedBy = EnumValue.Validator.class
)
public @interface EnumValue {
    String message() default "枚举值不正确";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    Class<? extends EnumCode> enumClass();

    class Validator implements ConstraintValidator<EnumValue, Object> {
        private Class<? extends EnumCode> enumClass;

        @Override
        public void initialize(EnumValue enumValue) {
            enumClass = enumValue.enumClass();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (null == value || "".equals(value)) {
                return Boolean.TRUE;
            }
            if (enumClass == null) {
                return Boolean.FALSE;
            }

            if (enumClass.isEnum()) {
                Object[] objs = enumClass.getEnumConstants();
                for (int i = 0; i < objs.length; i++) {
                    EnumCode enumCode = (EnumCode) objs[i];
                    if (enumCode.getCode().equals(value)) {
                        return Boolean.TRUE;
                    }
                }
            }
            return Boolean.FALSE;
        }
    }
}
